package com.yeqian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeqian.user.entity.RoleInfo;
import com.yeqian.user.mapper.PermissionMapper;
import com.yeqian.user.mapper.RoleInfoMapper;
import com.yeqian.user.service.RoleInfoService;
import com.yeqian.vo.PageVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleInfoServiceImpl extends ServiceImpl<RoleInfoMapper, RoleInfo> implements RoleInfoService {

    @Resource
    private RoleInfoMapper roleInfoMapper;

    @Resource
    private PermissionMapper permissionMapper;

    /**
     * 根据角色id查询角色与权限集合
     * @param id
     * @return
     */
    @Override
    public List<String> getUserRoleById(String id) {
        // 设置角色
        List<String> userRoleById = roleInfoMapper.getUserRoleById(id);
        List<String> addlist = new ArrayList<>();
        userRoleById.stream().forEach(roleCode -> {
            // 权限的格式:ROLE_xxx,而数据库中存储的只有xxx，ROLE_是拼接的，所以在这里需要处理一下
            String code=roleCode.split("_")[1];
            // 把角色对应的权限添加进列表
            addlist.addAll(permissionMapper.getPermissionByRoleCode(code));
        });
        userRoleById.addAll(addlist);
        return userRoleById.stream().distinct().collect(Collectors.toList());
    }

    /**
     * 查看角色列表
     * @param pageVO
     * @return
     */
    @Override
    public PageInfo<RoleInfo> listRoleInfo(PageVO pageVO) {
        PageHelper.startPage(pageVO.getPageNum(), pageVO.getPageSize());
        QueryWrapper<RoleInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("deleteflag","0");
        queryWrapper.orderByAsc("porder");
        List<RoleInfo> roleInfoList = roleInfoMapper.selectList(queryWrapper);
        return PageInfo.of(roleInfoList);
    }
}
